package com.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.lkd.entity.Business;
import com.lkd.entity.Node;
import com.lkd.entity.Region;
import com.lkd.mapper.BusinessMapper;
import com.lkd.mapper.NodeMapper;
import com.lkd.mapper.RegionMapper;
import com.lkd.mapper.VendingMachineMapper;
import com.lkd.service.NodeService;
import com.lkd.vo.NodeVo;
import com.lkd.vo.RegionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class NodeServiceImpl implements NodeService {

    @Autowired
    private NodeMapper nodeMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private VendingMachineMapper vendingMachineMapper;

    @Override
    public Boolean save(Node node) {
        node.setCreateTime(LocalDateTime.now());
        node.setUpdateTime(LocalDateTime.now());
        return nodeMapper.save(node);
    }

    @Override
    public Boolean update(Node node) {
        node.setUpdateTime(LocalDateTime.now());
        return nodeMapper.update(node);
    }

    @Override
    public Boolean deleteById(Long id) {
        return nodeMapper.deleteById(id);
    }

    @Override
    public NodeVo findById(Long nodeId) {

        Node node = nodeMapper.findById(nodeId);

        //根据区域id搞定区域VO
        Long regionId = node.getRegionId();
        Region region = regionMapper.findById(regionId);
        RegionVo regionVo = BeanUtil.copyProperties(region, RegionVo.class);
        Integer count = nodeMapper.countByRegionId(region.getId());
        regionVo.setNodeCount(count);

        //根据商圈id搞定商圈对象
        Integer businessId = node.getBusinessId();
        Business business = businessMapper.findById(businessId);

        //根据nodeid统计机器数量
        Integer vmCount = vendingMachineMapper.countByNodeId(node.getId());


        //组装返回
        NodeVo nodeVo = BeanUtil.copyProperties(node, NodeVo.class);
        nodeVo.setRegion(regionVo);
        nodeVo.setBusinessType(business);
        nodeVo.setVmCount(vmCount);

        return nodeVo;
    }
}
